package com.sdkj.fixed.asset.assets.service;

import com.github.pagehelper.PageHelper;
import com.sdkj.fixed.asset.api.assets.in_vo.AppApplyMaintain;
import com.sdkj.fixed.asset.api.assets.in_vo.MaintainRegisterExtend;
import com.sdkj.fixed.asset.api.assets.in_vo.SelPrams;
import com.sdkj.fixed.asset.api.assets.out_vo.WarehouseBase;
import com.sdkj.fixed.asset.api.assets.out_vo.WarehouseHistoryResult;
import com.sdkj.fixed.asset.api.login.pojo.LoginUser;
import com.sdkj.fixed.asset.assets.mapper.*;
import com.sdkj.fixed.asset.assets.util.*;
import com.sdkj.fixed.asset.common.base.BaseMapper;
import com.sdkj.fixed.asset.common.base.BaseService;
import com.sdkj.fixed.asset.common.base.PageParams;
import com.sdkj.fixed.asset.common.utils.JpushClientUtil;
import com.sdkj.fixed.asset.common.utils.TimeTool;
import com.sdkj.fixed.asset.pojo.assets.AssetLog;
import com.sdkj.fixed.asset.pojo.assets.MaintainRegister;
import com.sdkj.fixed.asset.pojo.assets.MaintainRegisterAssets;
import com.sdkj.fixed.asset.pojo.assets.Warehouse;
import com.sdkj.fixed.asset.pojo.system.PushManagement;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @author niuliwei
 * @description
 * @date 2020/7/27 10:37
 */
@Service
public class MaintainRegisterService extends BaseService<MaintainRegister> {

    @Autowired
    private MaintainRegisterMapper registerMapper;
    @Autowired
    private MaintainRegisterAssetsMapper registerAssetsMapper;
    @Autowired
    private WarehouseService warehouseService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private AssetLogMapper assetLogMapper;
    @Autowired
    private WarehouseMapper warehouseMapper;
    @Autowired
    private CacheUtils cacheUtils;
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private WarehouseHistoryMapper historyMapper;
    @Autowired
    private PushManagementMapper pushMapper;
    @Autowired
    private BorrowApplyMapper borrowApplyMapper;
    @Override
    public BaseMapper getMapper() {
        return registerMapper;
    }

    //获取订单号
    private String getNumber(String key, String orgId) {
        Long incr = redisUtil.getIncr(key +"_"+ orgId +"_"+ DateTools.dateToString(new Date(), "yyyyMMdd"), DateTools.expiresTime());
        if (incr == 0) {
            incr = redisUtil.getIncr(key +"_"+ orgId +"_"+ DateTools.dateToString(new Date(), "yyyyMMdd"), DateTools.expiresTime());
        }
        DecimalFormat df = new DecimalFormat("0000");
        return key + DateTools.dateToString(new Date(), "yyyyMMdd") + df.format(incr);
    }


    /**
     * app申请报修
     * @param params
     * @return
     */
    public MaintainRegister appApply (AppApplyMaintain params) throws Exception {
        String token = request.getHeader("token");
        String orgId = request.getHeader("orgId");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String userName = loginUser.getUserName();
        MaintainRegisterExtend register = new MaintainRegisterExtend();
        register.setAssetIdList(Arrays.asList(params.getId().split(",")));
        register.setRepairsContent(params.getNote());
        register.setImageUrl(params.getImageUrl());
        register.setState(1);
        register.setRepairsUserName(userName);
        register.setRepairsUser(userId);
        register.setDate(DateTools.dateToString(new Date(), "yyyy-MM-dd"));

        //获取资产管理员
        Warehouse info = warehouseService.selectByPrimaryKey(params.getId());
        register.setOperator(info.getAdmin());
        add(register, "APP");

        return register;
    }

    /**
     * 维修信息登记-新增
     * @param register
     * @return
     */
    public MaintainRegister add(MaintainRegisterExtend register, String type){
        String orgId = request.getHeader("orgId");
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();

        register.setNumber(getNumber("WX", orgId));
        register.setIsDeleted(0);
        if("PC".equals(type)){
            register.setCreateUser(userId);
            register.setUpdateUser(userId);
        }else if ("APP".equals(type)){
            register.setCreateUser("APP");
            register.setUpdateUser("APP");
        }
        register.setCreateDate(TimeTool.getCurrentTimeStr());
        register.setUpdateDate(TimeTool.getCurrentTimeStr());
        register.setOrgId(orgId);
        registerMapper.insertSelective(register);

        historyMapper.batchInsert(register.getAssetIdList() ,register.getId(),7);

        String afterState = "维修中";
        if("APP".equals(type)){
            afterState = "报修中";
        }
        for (String str : register.getAssetIdList()) {
            MaintainRegisterAssets asset = new MaintainRegisterAssets();
            asset.setMaintainInfoRegisterId(register.getId());
            asset.setAssetId(str);
            asset.setIsDeleted(0);
            asset.setCreateUser(userId);
            asset.setCreateDate(TimeTool.getCurrentTimeStr());
            asset.setUpdateUser(userId);
            asset.setUpdateDate(TimeTool.getCurrentTimeStr());
            Warehouse warehouse = warehouseMapper.selectByPrimaryKey(str);
            asset.setBeforeState(warehouse.getState());
            registerAssetsMapper.insertSelective(asset);

            stateLog(str, "维修信息登记", afterState, register.getOperator(), userId, register.getRepairsContent());
        }

        //修改资产状
        warehouseService.updateAssetState(register.getAssetIdList(), afterState, null, null);

        if("APP".equals(type)){
            //获取管理员
            List<String> a = borrowApplyMapper.getModelOrAssetAdmin(orgId, register.getAssetIdList().get(0), 1);
            TreeSet<String> set = new TreeSet<>();
            set.addAll(a);
            //推送消息给资产管理员
            String[] asia = set.toArray(new String[set.size()]);
            String notification_title = "资产报修";
            String msg_title = "资产报修";
            String msg_content = "资产报修, 单据编号：" + register.getNumber();
            JpushClientUtil.sendToAsia(asia, notification_title, msg_title, msg_content,"");
            Arrays.stream(asia).forEach(e->{
                PushManagement pu = new PushManagement();
                pu.setCompanyId(orgId);
                pu.setContent(msg_content);
                pu.setCtime(DateTools.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
                pu.setCuser(userId);
                pu.setSender(e);
                pu.setResult(0);
                pushMapper.insertSelective(pu);
            });
        }
        return register;
    }
    /**
     * 维修信息登记-分页查询
     * @param param
     * @return
     */
    public List<MaintainRegisterExtend> getAllPage(PageParams<SelPrams> param){
        String token = request.getHeader("token");
        String orgId = request.getHeader("orgId");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        Integer i = reportMapper.selectUserIsAllDataAuth(userId);
        if(i==1){
            userId = null;
        }
        PageHelper.startPage(param.getCurrentPage(), param.getPerPageTotal());
        List<MaintainRegisterExtend> list = registerMapper.getMaintainRegister(param.getParams().getStartDate(), param.getParams().getEndDate(), orgId, userId, null);
        if(list != null && list.size()>0){
            for (MaintainRegisterExtend extend : list) {
                List<WarehouseHistoryResult> results = historyMapper.queryWarehouseHistory(extend.getId(),7);
                List<WarehouseBase> listBase = new ArrayList<>();
                results.stream().forEach(w->{
                    WarehouseBase base = new WarehouseBase();
                    BeanUtils.copyProperties(w, base);
                    listBase.add(base);
                });
                extend.setResults(listBase);
            }
        }
        return list;
    }

    /**
     * 维修信息登记-查看详情
     * @param id
     * @return
     */
    public MaintainRegisterExtend selById(String id){
        MaintainRegisterExtend extend = registerMapper.selById(id);
        List<WarehouseHistoryResult> results = historyMapper.queryWarehouseHistory(extend.getId(),7);
        List<WarehouseBase> listBase = new ArrayList<>();
        results.stream().forEach(w->{
            WarehouseBase base = new WarehouseBase();
            BeanUtils.copyProperties(w, base);
            listBase.add(base);
        });
        extend.setResults(listBase);
        return extend;
    }

    /**
     * 维修信息登记-导出
     * @param startDate
     * @param endDate
     * @return
     */
    public List<MaintainRegisterExtend> exportExcel(String startDate, String endDate, String orgId, String token){
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        Integer i = reportMapper.selectUserIsAllDataAuth(userId);
        if(i==1){
            userId = null;
        }
        List<MaintainRegisterExtend> list = registerMapper.getMaintainRegister(startDate, endDate, orgId, userId, null);
        if(list != null && list.size()>0){
            for (MaintainRegisterExtend extend : list) {
                List<WarehouseHistoryResult> results = historyMapper.queryWarehouseHistory(extend.getId(),7);
                List<WarehouseBase> listBase = new ArrayList<>();
                results.stream().forEach(w->{
                    WarehouseBase base = new WarehouseBase();
                    BeanUtils.copyProperties(w, base);
                    listBase.add(base);
                });
                extend.setResults(listBase);
            }
        }
        return list;
    }

    /**
     * 维修信息登记-编辑
     * @return
     */
    public void updateInfo(MaintainRegisterExtend register){
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();

        register.setUpdateUser(userId);
        register.setUpdateDate(TimeTool.getCurrentTimeStr());
        registerMapper.updateByPrimaryKeySelective(register);
    }

    /**
     * 维修信息登记-开始维修
     * @return
     */
    public void maintainStart(String id){
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String userName = loginUser.getUserName();

        MaintainRegister register = new MaintainRegister();
        register.setId(id);
        register.setState(2);
        registerMapper.updateByPrimaryKeySelective(register);

        MaintainRegister reg = registerMapper.selectByPrimaryKey(id);
        //添加维修日志
        List<String> assetIdList = registerMapper.getMaintainRegAssetId(id);
        assetIdList.stream().forEach(e->{
            stateLog(e, "维修信息登记", "维修中", userName, userId, reg.getRepairsContent());
        });
        //修改资产状
        warehouseService.updateAssetState(assetIdList, "维修中", null, null);
    }

    /**
     * 维修信息登记-删除（超管权限）
     * @return
     */
    public void delById(String id){
        MaintainRegister register = new MaintainRegister();
        register.setId(id);
        register.setIsDeleted(1);
        registerMapper.updateByPrimaryKeySelective(register);
    }

    /**
     * 维修信息登记-维修完成
     * @return
     */
    public void maintainEnd(String id){
        String orgId = request.getHeader("orgId");
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userName = loginUser.getUserName();
        String userId = loginUser.getUserId();

        MaintainRegister register = new MaintainRegister();
        register.setId(id);
        register.setState(3);
        registerMapper.updateByPrimaryKeySelective(register);

        MaintainRegister reg = registerMapper.selectByPrimaryKey(id);

        //维修完成还原资产之前的状态
        Example example = new Example(MaintainRegisterAssets.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("maintainInfoRegisterId", id);
        List<MaintainRegisterAssets> list = registerAssetsMapper.selectByExample(example);
        list.stream().forEach(e->{

           //添加日志
            Warehouse wa = warehouseMapper.selectByPrimaryKey(e.getAssetId());
            String logContent = "资产【"+wa.getAssetName()+"】的"
                    + ChangLogUtil.simpleLogContxt(new LogContext(wa.getState(), e.getBeforeState()))
                    +"维修完成；"
                    +"维修内容："+ reg.getRepairsContent();
            AssetLog assetLog = new AssetLog();
            assetLog.setAssetId(e.getAssetId());
            assetLog.setLogType("维修信息登记");
            assetLog.setHandlerId(userId);
            assetLog.setHandlerUser(userName);
            assetLog.setHandlerContext(logContent);
            assetLog.setCreateUser(userId);
            assetLog.setCreateTime(TimeTool.getCurrentTimeStr());
            assetLogMapper.insertSelective(assetLog);

            Warehouse warehouse = new Warehouse();
            warehouse.setState(e.getBeforeState());
            warehouse.setAssetId(e.getAssetId());
            warehouseMapper.updateByPrimaryKeySelective(warehouse);
        });


        //如果有报修人，则推送消息
        MaintainRegister mr = registerMapper.selectByPrimaryKey(id);
        if(StringUtils.isNotBlank(mr.getRepairsUser())){
            String[] asia = {mr.getRepairsUser()};
            String notification_title = "维修完成";
            String msg_title = "维修完成";
            String msg_content = "维修完成，维修单号：" + mr.getNumber();
            JpushClientUtil.sendToAsia(asia, notification_title, msg_title, msg_content,"");

            PushManagement pu = new PushManagement();
            pu.setCompanyId(orgId);
            pu.setContent(msg_content);
            pu.setCtime(DateTools.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            pu.setCuser(userId);
            pu.setSender(mr.getRepairsUser());
            pu.setResult(0);
            pushMapper.insertSelective(pu);
        }
    }

    /**
     * 资产处理日志
     * @param assetId
     * @param modelName
     * @param afterState
     * @param handlerUser
     * @param handlerUserId
     */
    public void stateLog(String assetId, String modelName, String afterState, String handlerUser, String handlerUserId, String context){
        Warehouse warehouse = warehouseMapper.selectByPrimaryKey(assetId);
        String logContent = "资产【"+warehouse.getAssetName()+"】的"
                + ChangLogUtil.simpleLogContxt(new LogContext(warehouse.getState(), afterState))
                +"维修内容："+context;
        AssetLog assetLog = new AssetLog();
        assetLog.setAssetId(assetId);
        assetLog.setLogType(modelName);
        assetLog.setHandlerId(handlerUserId);
        assetLog.setHandlerUser(handlerUser);
        assetLog.setHandlerContext(logContent);
        assetLog.setCreateUser(handlerUserId);
        assetLog.setCreateTime(TimeTool.getCurrentTimeStr());
        assetLogMapper.insertSelective(assetLog);
    }
}
